package com.coamc.xlsunit;

import java.io.Reader;
import java.util.Map;
import java.util.Stack;

import org.beetl.core.Event;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Listener;
import org.beetl.core.Resource;
import org.beetl.core.engine.DefaultTemplateEngine;
import org.beetl.core.engine.StatementParser;
import org.beetl.core.statement.PlaceholderST;
import org.beetl.core.statement.Program;
import org.beetl.core.statement.Statement;
import org.beetl.core.statement.VarRef;
import org.beetl.sql.core.engine.SQLPlaceholderST;

import com.coamc.xlsunit.ExpressionVal.XLSUnitVarRef;

/**
 * 增强BeetlSQL引擎，能识别excel里的变量定义
 * 
 * @author xiandafu
 *
 */
public class BeetlSQLTemplateEngine extends DefaultTemplateEngine {
	public Program createProgram(Resource resource, Reader reader, Map<Integer, String> textMap, String cr,
			GroupTemplate gt) {
		Program program = super.createProgram(resource, reader, textMap, cr, gt);
		modifyStatemetn(resource, program, gt);

		return program;
	}

	private void modifyStatemetn(Resource resource, Program program, GroupTemplate gt) {
		Statement[] sts = program.metaData.statements;
		StatementParser parser = new StatementParser(sts, gt, resource.getId());

		parser.addListener(PlaceholderST.class, new XLSPlaceHolderListener());
		parser.addListener(VarRef.class, new XLSPlaceHolderListener());

		parser.parse();
	}

	static class XLSPlaceHolderListener implements Listener {

		public XLSPlaceHolderListener() {

		}

		@SuppressWarnings("rawtypes")
		@Override
		public Object onEvent(Event e) {
			Stack stack = (Stack) e.getEventTaget();
			Object o = stack.peek();
			if (o instanceof PlaceholderST) {
				PlaceholderST gf = (PlaceholderST) o;
				//沿用BeetlSQL的
				SQLPlaceholderST rf = new SQLPlaceholderST(gf);
				return rf;
			} else if (o instanceof VarRef) {
				VarRef ref = (VarRef) o;
				XLSSQLVarRef sqlRef = new XLSSQLVarRef(ref);
				return sqlRef;
			} else {
				return null;
			}
		}
	}

}
